package cmd

import (
	"file-cleaner/internal/logger"
	"github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

const configFile = "file-cleaner.yml"
const configPath = "./"

func genConfigCmd() *cobra.Command {
	configCmd := &cobra.Command{
		Use:   "config",
		Short: "Use config file instead of cmdline",
		Long:  `Use config file instead of cmdline.`,
		PreRun: func(cmd *cobra.Command, args []string) {
			initConfig()
		},
		Run: func(cmd *cobra.Command, args []string) {
			parseVarsByConfig()
			//fmt.Println("config")
			var cleaner fileCleaner
			switch method {
			case "dryrun":
				cleaner = genDryRunCleaner()
			case "remove":
				cleaner = genDeleteFileCleaner()
			case "link":
				cleaner = genLinkFileCleaner()
			default:
				logger.Fatal("var 'method' not in:", "dryrun", "remove", "link")
				return
			}
			cleaner.run()
		},
	}

	configCmd.Flags().StringVarP(&cfgFile, "config", "c", configPath+configFile, "config file path and name")

	return configCmd
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {

	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		cobra.CheckErr(err)

		// Search config in home directory with name ".cmd" (without extension).
		viper.AddConfigPath(home)
		viper.AddConfigPath(configPath)
		viper.SetConfigName(configFile)
		viper.SetConfigType("yml")
	}
	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		logger.Errorf("Cannot find config, %v\n", err)
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			// Config file not found; ignore error if desired
			logger.Errorf("Config file not found; ignore error if desired\n")
		} else {
			// Config file was found but another error was produced
			viper.Set("method", "")
			err = viper.SafeWriteConfigAs(configPath + configFile)
			if err != nil {
				logger.Errorf("Write Config Failed, %v\n", err)
			}
		}
	}
}

func parseVarsByConfig() {
	timeType = viper.GetString("time-type")
	timeAfter = viper.GetString("time-after")
	timeBefore = viper.GetString("time-before")
	cascade = viper.GetBool("cascade")
	path = viper.GetString("path")
	goroutine = viper.GetInt("goroutine")
	method = viper.GetString("method")
}
